<template>
  <el-dialog title="投诉工单" :visible.sync="showComplaintEdit" width="50%">
    <div>
      <el-form class="complaintListEdit" ref="complaintListEdit" :model="complaintListEdit" :rules="complaintListEditrules" label-width="100px">
        <el-form-item label="后台单号">
          <span>{{complaintListEdit.xmbzNo}}</span>
        </el-form-item>
        <el-form-item label="配送时间">
          <span>{{complaintListEdit.deliveryStartTime}}~{{complaintListEdit.deliveryEndTime}}</span>
        </el-form-item>
        <el-form-item label="配送员">
          <span>{{complaintListEdit.delivery}}</span>
        </el-form-item>
        <el-form-item label="平台单号">
          <span v-if="complaintListEdit.platformNo">{{complaintListEdit.platformNo}}</span>
          <span v-else>-</span>
        </el-form-item>
        <el-form-item label="创建工单时间">
          <span>{{complaintListEdit.createTime}}</span>
        </el-form-item>

        <el-form-item label="部门失误类型">
          <div v-if="comStatus=='update'">
            <XmCascader size="small" clearable v-model="complaintEditor" :options="errorTypeList" separator=">" placeholder="请选择部门失误类型" style="width: 280px;" :props="{multiple: true, checkStrictly: true}" :config="{needLevelCheck: true}" filterable></XmCascader>
          </div>
          <span v-if="comStatus=='create'">{{complaintListEdit.responsibleDepartmentErrorText}}</span>
        </el-form-item>

        <el-form-item label="投诉等级">
          <ComplaintLevelSelect v-model="complaintListEdit.complaintLevel" style="width: 150px;margin-right:10px" placeholder="请选择投诉等级" v-if="comStatus=='update'" size="small"></ComplaintLevelSelect>
          <span v-if="comStatus=='create'">{{complaintListEdit.complaintLevelName}}</span>
        </el-form-item>
        <el-form-item label="处理状态">
          <!-- <el-select v-model="complaintListEdit.handleState" placeholder="请选择处理状态" v-if="comStatus=='update'" size="small">
            <el-option :label="item.dictValue" :value="item.dictKey" v-for="(item,index) in dealstatusList" :key="index" size="small"></el-option>
          </el-select> -->
          <span>{{complaintListEdit.handleStateName}}</span>
        </el-form-item>
        <el-form-item label="投诉渠道">
          <ComplaintChannelSelect v-model="complaintListEdit.complaintChannel" style="width: 150px;margin-right:10px" placeholder="请选择投诉等级" v-if="comStatus=='update'" size="small"></ComplaintChannelSelect>
          <span v-if="comStatus=='create'">{{complaintListEdit.complaintChannelName}}</span>
        </el-form-item>
        <el-form-item label="责任人" prop="personLiable">
          <el-input v-model.trim="complaintListEdit.personLiable" v-if="comStatus=='update'" size="small" class="inputType" type="textarea" maxlength="10" show-word-limit></el-input>
          <span v-if="comStatus=='create'">{{complaintListEdit.personLiable}}</span>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model.trim="complaintListEdit.phone" onkeyup="value=value.replace(/[^\-?\d.]/g,'').slice(0,11)" onafterpaste="value=value.replace(/[^\-?\d.]/g,'').slice(0,11)" v-if="comStatus=='update'" class="inputType" size="small"></el-input>
          <span v-if="comStatus=='create'">{{complaintListEdit.phone}}</span>
        </el-form-item>
        <el-form-item label="投诉内容 " required>
          <el-input type="textarea" v-model.trim="complaintListEdit.complaintContent" v-if="comStatus=='update'" maxlength="500" show-word-limit :autosize="{ minRows: 4, maxRows:6}"></el-input>
          <div v-if="comStatus=='create'" class="processingResults">{{complaintListEdit.complaintContent}}</div>
        </el-form-item>
        <el-form-item label="处理结果" required>
          <el-input v-model.trim="complaintListEdit.processingResults" v-if="comStatus=='update'" type="textarea" maxlength="250" show-word-limit :autosize="{ minRows: 4}"></el-input>
          <div v-if="comStatus=='create'" class="processingResults">{{complaintListEdit.processingResults}}</div>
        </el-form-item>

        <!-- 投诉工单 -->
        <el-form-item label="图片附件:" prop="title">
          <div style="margin-bottom: 15px;">
            <el-upload action="/api/xmbz-goods/file/upload" :data="{tag:'complaint'}" list-type="picture-card" :on-success="handComplaintLeftSuccess" :limit="10" :file-list="singcomplaintForm.pics" :on-remove="beforeComplaintRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </el-form-item>

        <div class="buttontips">
          <el-button type="primary" plain @click="handlerEditcomplaint(complaintListEdit)" size="small" v-show="complaintShow">编辑</el-button>
          <div class="rows" v-if="complaintOther">
            <el-button type="danger" @click="handlerNotrefund(complaintListEdit)" size="small">退款不退货</el-button>

            <el-button type="danger" plain @click="handlercomplaintRefund(complaintListEdit)" size="small">申请退款</el-button>
            <el-button type="warning" plain @click="handlerProblemticket(complaintListEdit)" size="small">转到问题工单</el-button>
            <el-button type="info" size="small" plain @click="handlerLogcomplaint(complaintListEdit)">日志</el-button>
          </div>
        </div>
        <div v-if="complaintEditShow" class='ta-c'>
          <el-button class="mr-100" type="success" size="small" plain @click="handlerSavecomplaint(0)">保存</el-button>
          <!-- 最新添加的摁钮 -->
          <el-button v-for="item in dealstatusList.filter(item => item.dictValue != '已驳回')" :key="item.dictKey" :type="getBtnType(item)" size="small" plain @click="handlerSavecomplaint(item.dictKey)" class="ml=10">{{item.dictValue}}</el-button>
        </div>
      </el-form>
    </div>

    <!-- 退款不退货 投诉 -->
    <el-dialog title="退款不退货" :visible.sync="NotrefundVisible" :show-close="false" :before-close="handleCloseNotrefund" :append-to-body="true">
      <notrefund :complaintListEditnot="complaintListEdit" @close="handelNotrefundReset"></notrefund>
    </el-dialog>
    <!-- 投诉申请退款 -->
    <el-dialog title="投诉申请退款" :visible.sync="complaintRefundVisible" :show-close="false" :before-close="handleClose" :append-to-body="true">
      <complaintRefund :complaintListEdit="complaintListEdit" @close="handelcomplaintDialogReset"></complaintRefund>
    </el-dialog>
    <orderLogDialog ref="orderLogDialog" :append-to-body="true"></orderLogDialog>
  </el-dialog>
</template>

<script>
import notrefund from "@/components/notrefund" // 投诉退货不退款申请
import complaintRefund from "@/components/workorder" // 投诉退款申请
import orderLogDialog from '@/components/dialog/orderLogDialog'
import {
  getHandleStateList, //处理状态
  getComplaintChannelList,
  updateWorkOrderComplaint,
  transferWorkOrderProblem,
} from "@/api/workorder"

export default {
  props: {
    errorTypeList: {
      type: Array,
      default: () => []
    },
  },
  data() {
    return {
      showComplaintEdit: false,
      complaintEditor: [],
      singcomplaintForm: {   //投诉图片数组
        pics: []
      },
      complaintListEditrules: {
        personLiable: [
          {
            required: true,
            max: 10,
            message: "长度在10个字符以内",
            trigger: "blur"
          }
        ],
        provisionsContent: [
          {
            required: true,
            message: "投诉内容必填",
            trigger: "blur"
          }
        ],
        processingResults: [
          {
            required: true,
            message: "处理结果必填",
            trigger: "blur"
          }
        ]
      },
      complaintListEdit: {},
      comStatus: '',
      complaintEditShow: false,
      complaintShow: true,
      complaintOther: true, //投诉其他按钮
      NotrefundVisible: false,
      complaintRefundVisible: false,
      configTips: null,
      dealstatusList: []
    };
  },
  methods: {
    show(row, mode) {
      if (mode === 'view') {
        this.comStatus = 'create'
        this.complaintEditShow = false
        this.complaintOther = true
        this.complaintShow = true
      } else if (mode === 'update') {
        this.comStatus = "update"
        this.complaintShow = false
        this.complaintEditShow = true
        this.complaintOther = false
      }
      this.getHandleState()
      this.headleComplaintListDetils(row)
      this.showComplaintEdit = true
    },
    headleComplaintListDetils(row) {
      this.complaintEditor = row.responsibleDepartmentError.split(',')
      if (row.extJson) {
        this.singcomplaintForm.pics = JSON.parse(row.extJson).img.map(item => {
          return {
            url: item
          }
        })
      } else {
        this.singcomplaintForm.pics = []
      }

      this.complaintListEdit = row
      if (this.$refs['complaintListEdit'] !== undefined) {
        this.$refs['complaintListEdit'].resetFields()
      }
    },
    // 投诉工单 上传成功
    handComplaintLeftSuccess (response) {
      this.singcomplaintForm.pics.push({
        url: response.data
      })
    },
    // 投诉工单 删除
    beforeComplaintRemove (index) {
      this.singcomplaintForm.pics.map((item, ids) => {
        if (item.uid == index.uid) {
          this.singcomplaintForm.pics.splice(ids, 1)
        }
      })
    },
    handlerEditcomplaint (row) {
      // 投诉编辑
      this.comStatus = "update"
      this.complaintshowEdit = row
      this.complaintShow = false
      this.complaintEditShow = true
      this.complaintOther = false
    },
    //退款不退货
    handlerNotrefund (item) {
      // console.log(item)
      if (item.handleState == "1" || item.handleState == "4") {
        this.$message({
          type: "warning",
          message: "只有结案状态才能申请退款不退货!"
        })
        return false
      } else {
        this.NotrefundVisible = true
      }
    },
    handleCloseNotrefund (done) {
      this.$confirm("确认关闭？")
        .then(() => {
          this.handelNotrefundReset()
          done()
        })
        .catch(() => { })
    },
    handelNotrefundReset () {
      this.NotrefundVisible = false
      this.$emit('getList')
    },
    // 投诉申请退款
    handlercomplaintRefund (item) {
      if (item.handleState == "1" || item.handleState == "4") {
        this.$message({
          type: "warning",
          message: "只有结案状态才能申请退款!"
        })
        return false
      } else {
        this.complaintRefundVisible = true
      }
    },
    handlerProblemticket (item) {
      if (item.handleState == "1" || item.handleState == "4") {
        this.$message({
          type: "warning",
          message: "只有结案状态才能转到问题工单!"
        })
        return false
      } else {
        // 投诉转到问题工单
        this.$confirm("确定投诉转到问题工单, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            transferWorkOrderProblem({
              workOrderComplaintId: item.id
            }).then(() => {
              this.$message({
                type: "success",
                message: "已转到问题工单!"
              })
              this.showComplaintEdit = false
              this.$emit('getList')
            })
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消转到问题工单"
            })
          })
      }
    },
    handleClose (done) {
      this.$confirm("确认关闭？")
        .then(() => {
          this.handelcomplaintDialogReset()
          done()
        })
        .catch(() => { })
    },
    handelcomplaintDialogReset () {
      this.complaintRefundVisible = false
      this.$emit('getList')
    },
    getHandleState () {
      // 投诉状态处理
      getHandleStateList("").then(response => {
        this.dealstatusList = response.data.data
      })
    },
    handlerSavecomplaint (submitType) {
      this.$refs['complaintListEdit'].validate(valid => {
        if (valid) {
          if (!this.complaintEditor.length) {
            this.$message({
              type: "warning",
              message: "部门失误类型不能为空"
            })
            return false
          } else if (this.complaintListEdit.complaintContent == "") {
            this.$message({
              type: "warning",
              message: "投诉内容不能为空"
            })
            return false
          } else if (this.complaintListEdit.processingResults == "") {
            this.$message({
              type: "warning",
              message: "处理结果不能为空"
            })
            return false
          } else {
            //投诉保存提交
            this.$confirm("确定修改好投诉工单信息了吗, 是否继续?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            })
              .then(() => {
                const params = this.getParams(submitType)
                updateWorkOrderComplaint(params).then(() => {
                  this.$message({
                    type: "success",
                    message: "保存成功"
                  })
                  this.$emit('getList')
                  this.showComplaintEdit = false
                })
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消修改"
                })
              })
          }
        } else {
          this.$message({
            type: "warning",
            message: "填写相关提交内容!"
          })
          return false
        }
      })
    },
    getParams(submitType) {
      const item = this.complaintListEdit
      const params = {
        id: item.id,
        responsibleDepartmentError: this.complaintEditor.map(item => item[item.length - 1]).join(',') || null,    //添加编辑 部门失误类型
        orderId: item.orderId,
        responsibleDepartment: item.responsibleDepartment, //		责任部门 1:客户责任 2:配送部 3:生产部 4:客服部 5:运营中心 6:系统责任
        departmentErrorType: item.departmentErrorType, //		部门失误类型
        complaintLevel: item.complaintLevel, //			投诉等级
        handleState: submitType == 0 ? item.handleState : submitType, //	投诉状态
        complaintChannel: item.complaintChannel, //			投诉渠道
        personLiable: item.personLiable, //			责任人
        platformNo: item.platformNo, //		第三方平台单号
        phone: item.phone, //		手机号
        refundAmount: item.refundAmount, //				退款金额
        damages: item.damages, //				赔偿金
        complaintContent: item.complaintContent, //				投诉内容
        processingResults: item.processingResults, //	  处理结果
        extJson: JSON.stringify({ 'img': this.singcomplaintForm.pics.map(item => item.url)}),   // 投诉图片列表
        submitType: submitType,
      }
      return params
    },
    handlerLogcomplaint(data) {
      this.$refs.orderLogDialog.show({orderId: data.orderId})
    },
    getBtnType(item) {
      const typeMap = {
        1: 'primary',
        2: 'success',
        3: 'danger',
      }
      return typeMap[item.dictKey] || ''
    }
  },
  components: {
    notrefund,
    complaintRefund,
    orderLogDialog
  }
};
</script>
<style lang="scss" scoped>
.complaintListEdit {
  .el-form-item {
    margin-bottom: 20px !important;
  }
}
.buttontips {
  margin-bottom: 10px;
  display: flex;
  justify-content: space-around;
}
</style>